﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class FoodProcessor : MonoBehaviour
{
    private const int m_MAX_FOOD_COUNT = 100;

    [SerializeField]
    private Food m_foodModel;
    private List<Food> m_foodList;
    private Sprite[] m_foodTextures;

    private void Awake()
    {
        m_foodModel.gameObject.SetActive(false);
    }
    private void OnEnable()
    {
        if (m_foodTextures == null)
            m_foodTextures = Resources.LoadAll<Sprite>("Images/Foods");
        if (m_foodList == null)
            m_foodList = new List<Food>();
    }
    private void Update()
    {
        if (m_foodList.Count < m_MAX_FOOD_COUNT)
        {
            var food_clone = m_CreateFood(MapSelfAdaptaionTool.gameRect.D_L, MapSelfAdaptaionTool.gameRect.U_R);
            m_foodList.Add(food_clone);
            food_clone.RemoveFoodEvent += () => { m_foodList.Remove(food_clone); };
        }
    }

    private Food m_CreateFood(Vector2 pRange_D_L, Vector2 pRange_U_R)
    {
        var food_clone = Instantiate(m_foodModel.gameObject, this.transform, false).GetComponent<Food>();
        food_clone.SetLocalPos(new Vector2(Random.Range(pRange_D_L.x, pRange_U_R.x), Random.Range(pRange_D_L.y, pRange_U_R.y)));
        food_clone.SetLocalRotate(Quaternion.Euler(new Vector3(0, 0, Random.Range(0, 360))));
        food_clone.SetColor(UtilityFunctions.GetRandomColor32());
        var textureIndex = Random.Range(0, m_foodTextures.Length);
        food_clone.SetSprite(m_foodTextures[textureIndex]);
        food_clone.gameObject.name = "food(clone)" + textureIndex.ToString();
        food_clone.gameObject.SetActive(true);
        return food_clone;
    }
}
